#include "mainwidget.h"
#include "./ui_mainwidget.h"

#include <QDebug>
#include <QMessageBox>

#include <opencv4/opencv2/opencv.hpp>
extern "C"{
#include <libavcodec/avcodec.h>
}

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

//    connect(&m_camera, SIGNAL(appending_frame(cv::Mat)),this,SLOT(onAppending_frame(cv::Mat)));

    connect(&m_capture, SIGNAL(appending_frame(AVFrame*)), this, SLOT(onAppending_YUVframe(AVFrame *)));
    updateCameraList();

    connect(&m_timer, SIGNAL(timeout()), this, SLOT(updateFPS()));
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::enableFps()
{
    m_timer.start(1000);
}

void MainWidget::disableFps()
{
    m_timer.stop();
}

void MainWidget::updateCameraList()
{
    auto cameras = QCameraInfo::availableCameras();
    for(auto& camera: cameras){
        ui->comboBox_cameralist->addItem(camera.deviceName());
        qDebug() << "description:" << camera.description() <<"\ndeviceName:" << camera.deviceName() << "\n orientation:" << camera.orientation();
    }
}


void MainWidget::on_pushButton_setting_clicked()
{
    m_setting.show();
}


void MainWidget::on_pushButton_opencamera_clicked()
{
    auto current_camera = ui->comboBox_cameralist->currentText();
    bool ret = m_capture.open(current_camera);
//    bool ret = m_camera.openCamea(current_camera);
    if(!ret){
        QMessageBox messagebox;
        messagebox.setText(QString("打开相机失败：%1").arg(current_camera));
        messagebox.exec();
    }

    enableFps();
}

void MainWidget::onAppending_YUVframe(AVFrame *frame)
{
        if(enable_fps){
            ++m_iFrame_count;
        }

        ui->widget_viewport->updateYuv422(frame->data[0],frame->data[1], frame->data[2], frame->width, frame->height);
        av_frame_free(&frame);
}

//void MainWidget::onAppending_frame(cv::Mat frame)
//{
//    if(enable_fps){
//        ++m_iFrame_count;
//    }
////    qDebug() << "width:" << frame.cols <<",height:"<< frame.rows;
//    cv::cvtColor(frame, frame, (int)cv::COLOR_BGR2RGB);
//    QImage img(frame.data, frame.cols, frame.rows, QImage::Format::Format_RGB888);
//    ui->widget_viewport->updateImage(img);
//}

void MainWidget::updateFPS()
{
    ui->label_fps->setText(QString::number(m_iFrame_count));
    m_iFrame_count = 0;
}

